from rest_framework import status
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from .serializer import CartSerializer
from buyHigh.utils.buyHighResponse import APIResponse
from .models import cartModel
from rest_framework.decorators import action
# Create your views here.
class cartView(GenericViewSet):
    serializer_class = CartSerializer
    queryset = cartModel.objects.all()
    permission_classes = [IsAuthenticated]
    authentication_classes = [JSONWebTokenAuthentication]
    @action(detail=False, methods=['post'])
    def add_cart(self, request, *args, **kwargs):
        user=request.user
        print(request.data)
        serializer = CartSerializer(data=request.data,context={'user':user})
        if serializer.is_valid():
            serializer.save()
            return APIResponse(status=status.HTTP_200_OK, code=200, message='添加成功',statusCode=status.HTTP_200_OK)
        else:
            return APIResponse(status=status.HTTP_400_BAD_REQUEST, code=400, message=serializer.errors)
    @action(detail=False, methods=['get'])
    def get_cart_list(self, request, *args, **kwargs):
        user=request.user
        cart_queryset=cartModel.objects.filter(User_id=user.id)
        ser=CartSerializer(cart_queryset,many=True)
        return APIResponse(status=status.HTTP_200_OK, code=200, message='success',data=ser.data)
    @action(detail=False, methods=['delete'],url_path='delete_cart/(?P<cart_id>\d+)')
    def remove_cart(self, request, *args, **kwargs):
        user=request.user
        cart_id=kwargs.get('cart_id')
        cart_obj=cartModel.objects.filter(User_id=user.id,id=cart_id).first()
        if cart_obj:
            cart_obj.delete()
            return APIResponse(status=status.HTTP_200_OK, code=200, message='删除成功')
        else:
            return APIResponse(status=status.HTTP_400_BAD_REQUEST, code=400, message='购物车不存在')
    @action(detail=False, methods=['put'],url_path='update_cart/(?P<cart_id>\d+)')
    def update_cart(self, request, *args, **kwargs):
        user=request.user
        cart_id=kwargs.get('cart_id')
        num=request.data.get('num')
        cart_obj=cartModel.objects.filter(User_id=user.id,id=cart_id).first()
        if cart_obj:
            cart_obj.num=num
            cart_obj.save()
        else:
            return APIResponse(status=status.HTTP_400_BAD_REQUEST, code=400, message='购物车不存在')
        return APIResponse(status=status.HTTP_200_OK, code=200, message='success')
